﻿using Microsoft.Extensions.Caching.Memory;
using SocketGateway.Tool;
using TK.TSocket;

namespace SocketGateway
{
    /// <summary>
    /// MyHostedService
    /// </summary>
    public class MyHostedService : BackgroundService
    {
        private readonly ITcpSocketServer _sockerServer;
        private readonly IReceiveData _receviceData;
        private readonly Timer _timer;
        private readonly IMemoryCache _memoryCache;
        /// <summary>
        /// ctor
        /// </summary>
        public MyHostedService(
            ITcpSocketServer sockerServer,
            IReceiveData receviceData,
            IMemoryCache memoryCache)
        {
            _sockerServer = sockerServer;
            _receviceData = receviceData;
            _timer = new Timer(TimerCallback, null, 1000, 300000);
            _memoryCache = memoryCache;
        }

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _sockerServer.Start(_receviceData);
            foreach (var item in _sockerServer.TcpService.Monitors)
                Data.Listener.Add($"{item.IPHost.IP}:{item.IPHost.Port}");
            return Task.CompletedTask;
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            _sockerServer.Dispose();
            _timer.Dispose();
            return base.StopAsync(cancellationToken);
        }

        #region private methods
        /// <summary>
        /// Timer回调
        /// </summary>
        private void TimerCallback(object state)
        {
            foreach (var key in Data.LogData.Keys)
            {
                if (!_memoryCache.TryGetValue(key, out _)) 
                    Data.LogData.Remove(key);
            }
        }
        #endregion
    }
}
